<!-- 购物车界面 -->
<template>
	<!-- 头部操作部分 管理--结算--删除  -->
	<view class="title">
		<view class="">商品（{{cartData.length}}）</view>
		<view @click="operation" :style="{color:optionColor}">{{option}}</view>
	</view>

	<!-- 购物车部分 -->
	<view class="shopcart-view" v-for="(item,index) in cartData" :key="index">
		<!-- 多选部分 -->
		<view class="shopcart-icon">
			<icon type="success" color="#ea445a" v-if="item.isChecked" @click="select(index,item.isChecked)"></icon>
			<icon type="circle" v-else @click="select(index,item.isChecked)"></icon>
		</view>
		<!-- 商品图片 -->
		<view class="goods-img">
			<image :src="item.goods_image" mode="aspectFill"></image>
		</view>
		<!-- 商品信息 -->
		<view class="shopcart-right">
			<!-- 商品标题 -->
			<view class="overflow">{{item.goods_title}}</view>
			<!-- 商品规格，有规格展示规格 -->
			<view class="specs-show" v-if="item.specs.length > 0">
				<text v-for="(item2,index2) in item.specs" :key="index2">{{item2.att_val}}</text>
			</view>
			<view v-else class="specs-show" style="background-color: initial;"></view>
			<view class="shopcart-price">
				<view>¥{{item.goods_price}}</view>
				<view class="shopcart-amount">
					<image src="/static/images/sub.png" mode="aspectFit" @click="sub(item,index)" :class="[item.buy_amount == 1 ? 'prevent_style' : '']"></image>
					<text>{{item.buy_amount}}</text>
					<image src="/static/images/add.png" mode="aspectFit" @click="add(item,index)"></image>
				</view>
			</view>
		</view>
	</view>
	<!-- 没有数据的提示 -->
	<view class="tips" v-if="cartData.length == 0">购物车竟然是空的</view>

	<view style="height: 200rpx;"></view>
	<!-- 底部 -->
	<view class="shopcart-bottom">
		<!-- 取消全选 -->
		<block v-if="compute.selectAll">
			<icon type="success" color="#ea445a" @click="cancelSelect"></icon>
			<text class="space" @click="cancelSelect">全选</text>
		</block>

		<!-- 全选 -->
		<block v-else>
			<icon type="circle" color="#ea445a" @click="selectAll"></icon>
			<text class="space" @click="selectAll">全选</text>
		</block>

		<text class="cut-apart" :style="{opacity:bottomOpacity}"></text>
		<text class="space" :style="{opacity:bottomOpacity}">合计: </text>
		<text class="shopcart-total" :style="{opacity:bottomOpacity}">¥{{compute.price}}</text>
		<text class="shopcart-settle" :class="[compute.price <= 0 ? 'prevent_btn' : '']" @click="getInfo(option)">{{option == '管理' ? '结算' : '删除'}}</text>
	</view>

	<!-- 登陆弹窗 -->
	<Login></Login>
</template>

<script setup>
	import { ref, reactive, toRefs, computed, toRaw } from 'vue'
	import { onShow } from '@dcloudio/uni-app'
	import { FeedBack } from '../../public/package-js/feedBack';
	import Login from '@/components/login-view.vue'
	import { login_box } from '@/public/package-js/passValue.js'

	const data = reactive({
		cartData: [], //存放购物车数据
		bottomOpacity: 1, // 底部合计金额透明度
		optionColor: 'black',
	})
	const { cartData, num, bottomOpacity, optionColor } = toRefs(data)
	const db = wx.cloud.database()

	// 1、页面显示的时候执行
	onShow(() => {
		if (uni.getStorageSync('user_info')) {
			getCart()
		} else {
			data.cartData = []
		}
	})

	// 2、获取购物车数据
	async function getCart() {
		const res = await db.collection('shopping_cart').orderBy('add_time', 'desc').get()
		data.cartData = res.data
		// 遍历增加一个字段用于标记选中和未选中,一个小计字段
		data.cartData.forEach(item => {
			item.isChecked = false
			item.subtotal = item.goods_price * item.buy_amount
		})
	}

	// 2、点击管理
	const option = ref('管理')

	function operation() {
		option.value = option.value == '管理' ? '退出管理' : '管理'
		data.bottomOpacity = option.value == '管理' ? 1 : 0
		data.optionColor = option.value == '管理' ? 'black' : 'red'
	}

	// 3、减少数量
	async function sub(item, index) {
		data.cartData[index].buy_amount--
		data.cartData[index].subtotal = parseFloat((data.cartData[index].goods_price * data.cartData[index].buy_amount).toFixed(10))
		db.collection('shopping_cart').doc(item._id).update({
			data: {
				buy_amount: data.cartData[index].buy_amount,
				subtotal: data.cartData[index].subtotal
			}
		})
	}
	// 4、增加数量
	async function add(item, index) {
		if (item.specs.length != 0) {
			// 有规格，判断规格的库存
			const res = await db.collection('sku_data').where({ sku_id: item.goods_id }).get()
			try {
				res.data[0].sku.forEach(item2 => {
					if (item2.attribute[0].att_val == item.specs[0].att_val && item2.attribute[1].att_val == item.specs[1].att_val) {
						if (data.cartData[index].buy_amount >= item2.stock) {
							new FeedBack('库存不足', 'none').toast()
							throw ('库存不足')
						}
					}
				})
			} catch (e) {
				return false
			}

		} else {
			// 没有规格
			const res = await db.collection('goods').doc(item.goods_id).get()
			if (data.cartData[index].buy_amount >= res.data.stock) {
				new FeedBack('库存不足', 'none').toast()
				return false
			}
		}
		// 数量增加
		data.cartData[index].buy_amount++
		// 总计
		data.cartData[index].subtotal = parseFloat((data.cartData[index].goods_price * data.cartData[index].buy_amount).toFixed(10))
		db.collection('shopping_cart').doc(item._id).update({
			data: {
				buy_amount: data.cartData[index].buy_amount,
				subtotal: data.cartData[index].subtotal,
			}
		})
	}

	// 5、单个商品的选中或者取消选中
	function select(index, isChecked) {
		data.cartData[index].isChecked = data.cartData[index].isChecked ? false : true
	}

	// 6、全选
	function selectAll() {
		data.cartData.forEach(item => item.isChecked = true)
	}

	// 7、取消全选
	function cancelSelect() {
		data.cartData.forEach(item => item.isChecked = false)
	}

	// 8、监听全选或者取消全选
	const compute = computed(() => {
		let sum = 0
		let arr = []
		data.cartData.forEach(item => {
			if (item.isChecked) {
				sum += item.subtotal
				arr.push(item.isChecked)
			}
		})
		return {
			price: parseFloat((sum).toFixed(10)),
			selectAll: arr.length == data.cartData.length ? true : false /* true代表全选*/
		}
	})


	// 9、结算和删除
	function getInfo(val) {
		if (val == '管理') { //结算
			// console.log('结算')
			const res = data.cartData.filter(item => item.isChecked)

			// 过滤一下 isChecked字段
			const newArray = res.map(({ isChecked, ...rest }) => rest);
			// console.log("newArray",newArray);

			const order = JSON.stringify(newArray)
			uni.navigateTo({ //direct单个商品下单
				url: `/pages/confirm-order/confirm-order?order=${order}&type=cart`
			})
		} else { //删除
			uni.showModal({
				title: '提示',
				content: '确定所选商品吗？',
				success: async function(res) {
					if (res.confirm) {
						data.cartData.forEach(async (item, index) => {
							if (item.isChecked) {
								await db.collection('shopping_cart').doc(item._id).remove()
								data.cartData.splice(data.cartData.findIndex(item2 => item2._id == item._id), 1)
								new FeedBack("删除成功", "success").toast()
							}
						})
					} else if (res.cancel) {
						new FeedBack("取消操作", "error").toast()
					}
				}
			});


		}
	}
</script>

<style>
	page {
		background-color: #f4f4f4;
	}

	.title {
		background-color: #FFFFFF;
		display: flex;
		padding: 20rpx;
		/* border: 1px solid red; */
		justify-content: space-between;
	}

	.shopcart-view {
		background-color: #FFFFFF;
		display: flex;
		padding: 40rpx 20rpx;
		margin: 20rpx 12rpx;
		border-radius: 16rpx;
	}

	.shopcart-icon {
		height: 150rpx;
		display: flex;
		align-items: center;
	}

	.goods-img {
		width: 150rpx;
		height: 150rpx;
		padding: 0 20rpx;
	}

	.goods-img image {
		width: 150rpx;
		height: 150rpx;
		border-radius: 7rpx;
	}

	.shopcart-right {
		flex: 1;
	}

	.specs-show {
		background-color: #fafafa;
		color: #bdbdbd;
		display: inline-block;
		margin: 10rpx 0 20rpx 0;
		padding: 5rpx 10rpx;
		font-size: 26rpx;
	}

	.specs-show image {
		width: 20rpx;
		height: 20rpx;
		padding-left: 10rpx;
	}

	.shopcart-price {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.shopcart-price view:nth-child(1) {
		color: #ff4b70;
		font-weight: bold;
	}

	.shopcart-amount {
		display: flex;
		align-items: center;
		flex: 1;
		justify-content: flex-end;
	}

	.shopcart-amount image {
		width: 50rpx;
		height: 50rpx;
	}

	.shopcart-amount text {
		padding: 0 30rpx;
	}

	/* 底部购物车 */
	.shopcart-bottom {
		background-color: #ffffff;
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 100rpx;
		padding: 0 20rpx;
		display: flex;
		align-items: center;
	}

	.shopcart-bottom text {
		display: block;
	}

	.space {
		padding: 0 15rpx;
	}

	.shopcart-total {
		flex: 1;
		color: #dd4055;
		font-weight: bold;
	}

	.shopcart-settle {
		background-color: #ea445a;
		padding: 20rpx 50rpx;
		border-radius: 10rpx;
		color: #FFFFFF;
	}

	.cut-apart {
		width: 7rpx;
		height: 35rpx;
		background-color: #dadada;
	}

	.prevent_btn {
		opacity: 0.4;
		pointer-events: none;
	}
</style>
